<template>
  <yy-paging
    v-model="dataList"
    @query="queryList"
    ref="paging"
    :auto="false"
    @scroll="scroll"
    class="backgroundImage"
    :style="{ backgroundImage: `url(${vk.myfn.handleImageUrl(weather?.lives[0]?.top)})` }"
    :refresher-enabled="true"
  >
    <template #empty>
      <yy-empty></yy-empty>
    </template>
    <template #loadingMoreNoMore>
      <yy-nomore text=""></yy-nomore>
    </template>
    <template #top>
      <u-navbar
        :is-back="false"
        :background="{ backgroundColor: isScroll ? '#F2F5F7' : 'transparent' }"
        :border-bottom="false"
        :custom-style="{ transition: 'background-color 0.3s ease-in-out' }"
      >
        <view class="grid grid-cols-3 items-center px-3 w-full">
          <view class="flex col-span-1 items-center" @click="vk.navigateBack()">
            <image src="/static/dddr128.png" mode="aspectFill" class="size-6" />
          </view>
          <view class="line-clamp-1 flex col-span-1 justify-center">
            <view class="text-[#000] font-bold text-base"> {{ address }} </view>
          </view>
          <view class="flex col-span-1 justify-end">
            <view class="text-[14px] text-[#5C6068]"> </view>
          </view>
        </view>
      </u-navbar>
    </template>
    <view class="flex flex-col gap-3">
      <view class="flex flex-col gap-3 p-4 pb-0">
        <view class="text-[.75rem] text-[#8E9299]"> 实时天气 · 更新于 {{ updatedOn }} </view>
        <view class="flex justify-between items-baseline">
          <view class="flex gap-1 items-baseline">
            <u-count-to
              :start-val="0"
              :end-val="weather?.lives?.[0]?.temperature"
              class="!text-[3.5rem] text-[#161A24] !font-bold"
            ></u-count-to>
            <view class="text-[3.5rem] text-[#161A24] font-bold"> °</view>
            <view class="text-[1rem] text-[#161A24]">{{ weather?.lives?.[0]?.weather || '-' }}</view>
          </view>
          <view class="text-[.6875rem] text-[#5C6068] flex items-center gap-1">
            {{ weather?.lives?.[0]?.weather_today || '-' }}
          </view>
        </view>
        <view class="grid grid-cols-4 gap-2">
          <view class="aspect-square bg-[#FFFFFF] rounded-[.5rem] p-3 flex flex-col justify-between">
            <view class="size-4">
              <image src="/static/dddr88.png" class="size-full" mode="aspectFill" />
            </view>
            <view class="text-[.8125rem] text-[#161A24] font-bold">{{ weather?.lives[0]?.windpower || '-' }}</view>
            <view class="text-[.6875rem] text-[#8E9299]">{{ weather?.lives[0]?.winddirection || '-' }}</view>
          </view>
          <view class="aspect-square bg-[#FFFFFF] rounded-[.5rem] p-3 flex flex-col justify-between">
            <view class="size-4">
              <image src="/static/dddr89.png" class="size-full" mode="aspectFill" />
            </view>
            <view class="text-[.8125rem] text-[#161A24] font-bold">{{ weather?.lives[0]?.aqi || '-' }}</view>
            <view class="text-[.6875rem] text-[#8E9299]">空气</view>
          </view>
          <view class="aspect-square bg-[#FFFFFF] rounded-[.5rem] p-3 flex flex-col justify-between">
            <view class="size-4">
              <image src="/static/dddr90.png" class="size-full" mode="aspectFill" />
            </view>
            <view class="text-[.8125rem] text-[#161A24] font-bold">{{ weather?.lives[0]?.humidity || '-' }}%</view>
            <view class="text-[.6875rem] text-[#8E9299]">湿度</view>
          </view>
          <view class="aspect-square bg-[#FFFFFF] rounded-[.5rem] p-3 flex flex-col justify-between">
            <view class="size-4">
              <image src="/static/dddr91.png" class="size-full" mode="aspectFill" />
            </view>
            <view class="text-[.8125rem] text-[#161A24] font-bold whitespace-nowrap"
              >{{ weather?.lives[0]?.pressure || '-' }} hPa</view
            >
            <view class="text-[.6875rem] text-[#8E9299]">气压</view>
          </view>
        </view>
      </view>
      <!-- 24小时天气预报 -->
      <!-- 24小时天气预报 -->
      <view class="bg-[#FFFFFF] rounded-[1rem_1rem_0rem_0rem] p-4 flex flex-col gap-3">
        <view class="flex justify-between">
          <view class="text-[.9375rem] text-[#161A24] font-bold"> 24小时天气预报 </view>
          <view class="text-[.625rem] text-[#8E9299] flex items-center gap-1">
            <view>{{ weather.hours24.sunrise }}</view>
            <view>{{ weather.hours24.sunset }}</view>
          </view>
        </view>

        <scroll-view scroll-x="true" class="whitespace-nowrap">
          <view class="flex flex-nowrap gap-[.125rem] w-full relative">
            <view class="absolute left-0 top-[25%] w-[77.875rem] h-[6.25rem]">
              <qiun-data-charts
                type="line"
                class=""
                :opts="t.opts"
                :chartData="t.chartData"
                :canvas2d="true"
                canvasId="GRPdCTumTiwuBshBczfTnyyikrxXednZ"
              />
            </view>
            <view
              class="flex flex-col w-[3.125rem] justify-center items-center flex-none gap-2"
              v-for="(i, k) in weather.hours24.list"
              :key="k"
            >
              <view class="text-[.6875rem] text-[#5C6068]">{{ i.date }}</view>
              <view class="size-6 mb-[6.25rem]" :class="i.icon_class"> </view>
              <view class="flex flex-col text-[.5625rem] text-[#5C6068] items-center">
                <view>{{ i.wind }} </view>
                <view>{{ i.power }} </view>
              </view>
              <view class="h-[1rem] w-full flex justify-center items-center" :class="aqiClass(i)">
                <view class="text-[.5625rem]"> {{ i.aqi }} </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <!-- 未来15日天气趋势 -->
      <!-- 未来15日天气趋势 -->
      <view class="bg-[#FFFFFF] p-4 flex flex-col gap-3">
        <view class="flex justify-between">
          <view class="text-[.9375rem] text-[#161A24] font-bold"> 未来7日天气趋势 </view>
        </view>
        <scroll-view scroll-x="true" class="relative whitespace-nowrap">
          <view class="absolute left-0 top-[34%] w-[27rem] h-[6.25rem]">
            <qiun-data-charts
              type="line"
              class=""
              :opts="tt.opts"
              :chartData="tt.chartData"
              :canvas2d="true"
              canvasId="GRPdCTumTiwuBshBczfTnyyikrxXednB"
            />
          </view>
          <view class="flex flex-nowrap gap-[.125rem] w-full">
            <view
              class="flex flex-col w-[3.75rem] justify-center items-center flex-none gap-2"
              v-for="(i, k) in weather?.forecasts?.[0]?.casts.slice(0, 7) || []"
              :key="k"
            >
              <view class="text-[.6875rem] text-[#5C6068]">{{ i.date }}</view>
              <view class="size-6" :class="i.icon_class"> </view>
              <!-- dayweather -->
              <view class="text-[.625rem] text-[#5C6068] mb-[6.25rem] r">{{ i.dayweather }}</view>
              <view class="flex flex-col text-[.5625rem] text-[#5C6068] items-center">
                <view class="r"> {{ i.daywind }} </view>
                <view>{{ i.daypower }} </view>
              </view>
              <view class="h-[1rem] w-full flex justify-center items-center" :class="aqiClass(i)">
                <view class="text-[.5625rem]"> {{ i.aqi }} </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </yy-paging>
</template>

<script>
  export default {
    data() {
      return {
        isScroll: false,
        dataList: [],
        automatic: false,
        id: '',
        weather: {
          lives: [],
          hours24: {}
        },
        address: '',
        options: {},
        t: {
          chartData: {},
          opts: {
            color: ['#00A9AB'],
            padding: [0, 0, 0, 0],
            dataLabel: true,
            dataPointShape: true,
            legend: {
              show: false
            },
            xAxis: {
              disabled: true,
              disableGrid: true,
              axisLine: false,
              // itemCount: 7,
              scrollShow: true
            },
            yAxis: {
              disabled: true,
              axisLine: false,
              disableGrid: true,
              gridType: 'dash',
              dashLength: 2,
              data: []
            },
            extra: {
              line: {
                type: 'curve',
                width: 2,
                activeType: 'solid',
                linearType: 'custom',
                onShadow: true,
                animation: 'vertical'
              }
            }
          }
        },
        tt: {
          chartData: {},
          opts: {
            color: ['#FF9A07', '#00A9AB'],
            padding: [0, 0, 0, 0],
            dataLabel: true,
            dataPointShape: true,
            legend: {
              show: false
            },
            xAxis: {
              disabled: true,
              disableGrid: true,
              axisLine: false,
              // itemCount: 7,
              scrollShow: true
            },
            yAxis: {
              disabled: true,
              axisLine: false,
              disableGrid: true,
              gridType: 'dash',
              dashLength: 2,
              data: []
            },
            extra: {
              line: {
                type: 'curve',
                width: 2,
                activeType: 'solid',
                linearType: 'custom',
                onShadow: true,
                animation: 'vertical'
              }
            }
          }
        }
      }
    },
    onLoad(options) {
      this.options = options
      setTimeout(() => {
        this.$refs.paging.reload()
      }, 0)
    },
    computed: {
      updatedOn() {
        const reportTime = this.weather?.lives?.[0]?.reporttime
        if (!reportTime || reportTime === '-') return '-'

        const now = new Date()
        const reportDate = new Date(reportTime)
        const diffMs = now - reportDate

        // 转换为分钟
        const minutes = Math.floor(diffMs / 1000 / 60)

        if (minutes < 1) return '刚刚'
        if (minutes < 60) return `${minutes}分钟前`

        // 转换为小时
        const hours = Math.floor(minutes / 60)
        if (hours < 24) return `${hours}小时前`

        // 转换为天
        const days = Math.floor(hours / 24)
        if (days < 30) return `${days}天前`

        // 超过30天显示具体日期
        return reportTime.split(' ')[0]
      }
    },
    methods: {
      aqiClass(i) {
        const aqiMap = {
          优: 'wea-aqi-1',
          良: 'wea-aqi-2',
          轻度: 'wea-aqi-3',
          中度: 'wea-aqi-4',
          重度: 'wea-aqi-5',
          严重: 'wea-aqi-6'
        }
        return aqiMap[i.aqi] || ''
      },
      scroll(e) {
        this.isScroll = e.detail.scrollTop > 0
      },
      async queryList(page, limit) {
        const { data } = await api.getWeather({
          adcode: this.options.adcode
        })
        console.log('data==> ', data)

        this.weather = data
        const city = data?.forecasts?.[0]?.city || ''
        const district = data?.forecasts?.[0]?.district || ''
        this.address = city === district ? city : `${city}${district}`

        //24小时天气预报
        //24小时天气预报
        let temperature = {
          categories: data.hours24.list.map(item => item.date),
          series: [
            {
              name: '温度',
              data: data.hours24.list.map(item => item.temp)
            }
          ]
        }
        let n = 6
        this.t.opts.yAxis.data = [
          {
            min: Math.min(...data.hours24.list.map(item => item.temp)) - n,
            max: Math.max(...data.hours24.list.map(item => item.temp)) + n
          }
        ]
        this.t.chartData = JSON.parse(JSON.stringify(temperature))
        // 未来15日天气趋势
        // 未来15日天气趋势
        const sevenDayForecasts = data.forecasts[0].casts.slice(0, 7)
        let temperatures = {
          categories: sevenDayForecasts.map(item => item.date),
          series: [
            {
              name: '最高温',
              data: sevenDayForecasts.map(item => item.daytemp)
            },
            {
              name: '最低温',
              data: sevenDayForecasts.map(item => item.nighttemp)
            }
          ]
        }

        // 获取两条折线的所有温度数据
        const allTemps = [
          ...sevenDayForecasts.map(item => Number(item.daytemp)),
          ...sevenDayForecasts.map(item => Number(item.nighttemp))
        ]

        this.tt.opts.yAxis.data = [
          {
            min: Math.min(...allTemps) - n,
            max: Math.max(...allTemps) + n
          }
        ]
        this.tt.chartData = JSON.parse(JSON.stringify(temperatures))

        this.$refs.paging.complete([''])
      }
    }
  }
</script>

<style lang="scss" scoped>
  .backgroundImage {
    background-repeat: no-repeat !important;
    background-size: 100% !important;
    background-position: top !important;
  }
</style>
